package com.qf.fcy.youshare.utils;

/**
 * Created with IntelliJ IDEA.
 * User: Alex[FR]
 * Date: 2015/2/5
 * Email: alex_fcy@163.com
 */

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Set;

/**
 * HTTP网络请求的工具类，包含了GET, POST, PUT, DELETE 这四种请求方法的支持
 */
public class HttpClientHelper {
    // TODO GET 请求


    /**
     * 执行 GET 请求
     *
     * @param url 请求的网址
     * @return byte[] 网络数据
     */
    public static byte[] get(String url) {
        byte[] ret = null;
        if (url != null) {
            HttpGet request = new HttpGet(url);
            ret = directRequest(request);
        }

        return ret;
    }

    /**
     * 执行 DELETE 请求
     *
     * @param url
     * @return
     */
    public static byte[] delete(String url) {
        byte[] ret = null;
        if (url != null) {
            HttpDelete request = new HttpDelete(url);
            ret = directRequest(request);
        }

        return ret;
    }

    /**
     * 用于get和delete请求
     *
     * @param request
     * @return
     */
    public static byte[] directRequest(HttpRequestBase request) {
        byte[] ret = null;
        HttpClient httpClient = new DefaultHttpClient();
        try {
            HttpResponse response = httpClient.execute(request);
            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity entity = response.getEntity();
                ret = EntityUtils.toByteArray(entity);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return ret;
    }

    public static byte[] post(String url, HashMap<String, String> params) {
        return post(url, params, "UTF-8");
    }

    /**
     * 执行 POST 请求
     * POST请求要提交数据，提交数据的方式
     * 本方法采用 提交 key=value&key=value的形式
     * 这种数据格式就是网页中，form 表单提交的数据格式
     *
     * @param url    请求的网址
     * @param params HashMap 包含的参数，也就是 key=value的集合
     * @return byte[] 网络数据
     */
    public static byte[] post(String url, HashMap<String, String> params, String encoding) {
        byte[] ret = null;
        if (url != null) {
            HttpPost request = new HttpPost(url);
            ret = processEntityRequest(request, params, encoding);
        }
        return ret;
    }

    public static byte[] put(String url, HashMap<String, String> params, String encoding) {
        byte[] ret = null;
        if (url != null) {
            HttpPut request = new HttpPut(url);
            ret = processEntityRequest(request, params, encoding);
        }
        return ret;
    }

    /**
     * 本方法实现了POST请求与PUT请求，发送key=value形式的
     *
     * @param request
     * @param params
     * @param encoding
     * @return
     */
    private static byte[] processEntityRequest(
            HttpEntityEnclosingRequestBase request,
            HashMap<String, String> params, String encoding) {

        byte[] ret = null;
        if (request != null) {
            if (params != null) {
                // setEntity 用于设置提交的数据
                // 对于 key=value&key=value的形式，需要使用 UrlEncodedFormEntity
                LinkedList<NameValuePair> parameters = new LinkedList<NameValuePair>();
                // TODO 添加参数
                Set<String> keySet = params.keySet();
                for (String key : keySet) {
                    String value = params.get(key);
                    parameters.add(new BasicNameValuePair(key, value));
                }

                // 将 parameters 中的 key->value 通过 UrlEncodedFormEntity 进行组合
                // 形成 key=value&key=value的形式（这种形式是服务器标准数据提交的格式）
                if (encoding == null) {
                    encoding = "UTF-8";
                    try {
                        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters, encoding);
                        request.setEntity(entity);
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                }
            }

            HttpClient httpClient = new DefaultHttpClient();
            try {
                HttpResponse response = httpClient.execute(request);
                if (response.getStatusLine().getStatusCode() == 200) {
                    HttpEntity entity = response.getEntity();
                    ret = EntityUtils.toByteArray(entity);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

        return ret;

    }

}
